//
//  BoardViewController.m
//  CheckersGame
//
//  Created by  on 11-11-23.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "BoardViewController.h"
#import "GameManagedObject.h"
#import "Piece.h"
#import "AppDelegate.h"//fix this

@implementation BoardViewController

@synthesize toplevelView;
@synthesize boardView, timeout, player1, player2, pvp;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
@synthesize wroteGameResult, ai_player1, ai_player2;

-(void)synchToGameState : (CheckersGameState*) game {
    CheckersMove move;
	if (pieceArray){    
		for (Piece* piece in pieceArray){
			[piece removeFromSuperview];
		}
		pieceArray = nil;
	} 
    boardView.gameState = game;
    [boardView setNeedsDisplay];
    pieceArray = [Piece pieceArrayFromBoard: game View: boardView];
    for (Piece* piece in pieceArray){
        [self.toplevelView addSubview: piece];
    }
}

-(void) attemptNextMove {
    if (!timer) return;
    CheckersMove move;
    int game_result;
    if (gameState.moveAmount >= MAX_CHECKERS_GAME-1){
        NSLog(@"Game has drawn!");
        [self saveGameResult:DRAW];
        [self.navigationController popViewControllerAnimated:YES];
    }
        
    if (chbIsGameOver([gameState getBoardRef], &game_result)){
        NSLog(@"Player %d has won", game_result);
        [self saveGameResult:game_result];
        [self.navigationController popViewControllerAnimated:YES];
    } else if ( [[gameState currentPlayer] decideMove: &move Board: [gameState getBoardRef]] ) {
        [gameState makeMove: &move];
        [self synchToGameState: gameState];
        [boardView setNeedsDisplay];
    } 
}

- (void)saveGameResult:(result)winner
{
    if (self.wroteGameResult==YES) return;
    
    NSString *victor;
    NSString *loser;
    
    if (winner == PLAYER1)
    {
        victor = self.player1;
        loser = self.player2;
    }
    else
    {
        victor = self.player2;
        loser = self.player1;
    }
    
    NSLog(@"victor is %@ and loser is %@", victor, loser);
    
    // In the saved record the winner is stored in player1
    NSDictionary *game = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSDate date], @"date", 
                         (winner==DRAW)? @"1":@"0", @"draw", 
                         (self.pvp)? @"1":@"0", @"pvp",
                         victor, @"player1",
                         loser, @"player2", 
                         (self.ai_player1)? @"1":@"0", @"ai_1",
                         (self.ai_player2)? @"1":@"0", @"ai_2", nil];
    
    [GameManagedObject gameWithResult:game inManagedContext:self.managedObjectContext];
    [self saveContext];
    self.wroteGameResult = YES;
}

-(void)gameLoop {
    [self attemptNextMove];
}

-(IBAction)didClickBoard : (id)sender{
    gameState.pieceIsSelected = NO;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


// Controller was sent message for a new game
- (void)newGame : (CheckersGameState*) gs
{
    self.wroteGameResult = NO;
	gameState = gs;
	[self synchToGameState: gameState];
}

// Controller was sent message for a quit
- (IBAction)quit:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
   // [self newGame];
    //[self.navigationController setNavigationBarHidden:YES animated:YES];
    // Do any additional setup after loading the view from its nib.
    
    timer = [NSTimer scheduledTimerWithTimeInterval:0.033 target:self 
                                           selector:@selector(gameLoop) 
                                           userInfo:nil repeats:YES];
    
    self.navigationItem.rightBarButtonItem = 
        [[UIBarButtonItem alloc] initWithTitle:@"Undo" style:UIBarButtonItemStyleBordered 
                                        target:self action:@selector(didSelectUndo:)];
    self.navigationItem.title = self.player2;
    self->bottomBarTitle.text = self.player1;
}

- (void)viewDidDisappear:(BOOL)animated {
    [timer invalidate];
    timer = nil;
    gameState = nil;
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter]; 
    [center removeObserver: self];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
    //[self.navigationController setNavigationBarHidden:NO animated:YES];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)viewDidAppear:(BOOL)animated 
{
    [self becomeFirstResponder];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


-(IBAction)didSelectUndo: (id)sender {
    NSLog(@"undo occurred");
    [gameState unmakeMove];
    [self synchToGameState:gameState];
}

-(IBAction)didSelectPause:(UIBarButtonItem *)sender {
    //UIButton* but = (UIButton*) sender;
    
    [gameState togglePauseState];
    if (gameState.isPaused) 
    {
        sender.title = @"Resume";
        sender.style = UIBarButtonItemStyleDone;
    }
    else 
    {
        sender.title = @"Pause";
        sender.style = UIBarButtonItemStyleBordered;
    }
}

- (void) motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    
}

- (void) motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    [self didSelectUndo:nil];
}

#pragma mark - Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}

/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"CheckersGame" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"CheckersGame.sqlite"];
    
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return __persistentStoreCoordinator;
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges]) NSLog(@"context has changes to write");
        else NSLog(@"context does not have changes");
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
        if ([managedObjectContext hasChanges]) NSLog(@"context STILL has changes to write");
        else NSLog(@"context no longer has changes");
    }
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end
